package com.baiye.template.config;

import com.baiye.template.common.R;
import com.baiye.template.pojo.Role;
import com.baiye.template.pojo.User;
import com.baiye.template.service.UserService;
import com.baiye.template.utils.JwtUtils;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author GUOZHIPENG
 * @version 1.0
 * @date 2021/10/27 19:16
 * 登录成功处理逻辑
 */

@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        //更新用户表上次登录时间、更新人、更新时间等字段
        User userDetails = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        User sysUser = userService.selectByName(userDetails.getUsername());
//        sysUser.setLastLoginTime(new Date());
//        sysUser.setUpdateTime(new Date());
//        sysUser.setUpdateUser(sysUser.getId());
//        userService.update(sysUser);

        //此处还可以进行一些处理，比如登录成功之后可能需要返回给前台当前用户有哪些菜单权限，
        //进而前台动态的控制菜单的显示等，具体根据自己的业务需求进行扩展



        String token = JwtUtils.generateTokenExpireInMinutes(userDetails,24*60);
        //处理编码方式，防止中文乱码的情况
        httpServletResponse.setContentType("text/json;charset=utf-8");
        httpServletResponse.addHeader("Authorization", token);
        httpServletResponse.addHeader("Access-Control-Expose-Headers", "Authorization");

        Gson gson = new Gson();
        httpServletResponse.getWriter().write(gson.toJson(new R<>().login(userDetails,token)));
    }
}

